package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.aliyuncs.exceptions.ClientException;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Order;
import com.itheima.service.OrderService;
import com.itheima.utils.SMSUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.Map;

/**
 * @PackageName: com.itheima.controller
 * @ClassName: OrderController
 * @Author: XLB
 * @Date: 2020/3/9 20:16
 * @Description:
 */


/*
* 校验验证码
* 1.获取redis中储存的验证码
* 2.获取用户提交的验证码
* 3.校验验证码
*   4.false:直接返回错误 true：预约数据处理
*
* 预约数据处理
* 1.添加预约类型，执行到该方法肯定都是 微信预约
* 2.调用服务接口，完成数据处理
*   3.没有完成：预约数据处理失败
*     完成，预约数据处理成功
*           4，发送给短消息，预约成功的短信提醒
*
*
* */
@RestController
@RequestMapping("/order")
public class OrderController {
    @Reference
    private OrderService orderService;
    @Autowired
    private JedisPool jedisPool;
    @RequestMapping("/submit")
    public Result submit(@RequestBody Map map){
        String telephone = (String) map.get("telephone");
        //判断验证码是否正确
        //获得redis中的验证码
        String validateCodeInRedis = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_ORDER);

        //获得前台传入的验证码
        String validateCode = (String) map.get("validateCode");

        if (validateCodeInRedis!=null&&validateCode!=null&&validateCodeInRedis.equals(validateCode)){
            //设置预约类型，微信预约，或者是电话。。。。。
            map.put("orderType", Order.ORDERTYPE_WEIXIN);
            Result result =null;
            try {
                //在线预约
                result =  orderService.order(map);
            } catch (Exception e) {
                e.printStackTrace();
                //预约失败
                return result;
            }
            //预约成功的话，给用户发送短信
            if (result.isFlag()){
                try {
                    SMSUtils.sendShortMessage(SMSUtils.ORDER_NOTICE,telephone,(String) map.get("orderDate"));
                } catch (ClientException e) {
                    e.printStackTrace();
                }
            }
            return result;

        }else {
            //如果验证码不正确，返回结果给页面
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
    }

    @RequestMapping("/findById")
    public Result findById(Integer id){

        try {
            Map map = orderService.findById(id);
            return new Result(true,MessageConstant.QUERY_ORDER_SUCCESS,map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_ORDER_FAIL);
        }
    }
}
